package org.belkodevelop.photo.dao;

import org.belkodevelop.photo.domen.Photo;
import org.belkodevelop.user.domain.User;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author VMozolev
 */
@Repository
public class PhotoDAOimpl implements PhotoDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addPhoto(Photo photo) {
        sessionFactory.getCurrentSession().save(photo);
    }

    @Override
    public Photo getPhoto(long id) {
        return (Photo)sessionFactory.getCurrentSession().get(Photo.class, new Long(id));
    }

    @Override
    public List<Photo> getPhotos(long realtyId) {
        Criteria c = sessionFactory.getCurrentSession().createCriteria(Photo.class)
            .add(Restrictions.eq("realty.id", realtyId))
            .addOrder(Order.asc("datePublication"));
        return c.list();
    }

    @Override
    public boolean deletePhoto(long id) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("delete from Photo where id = :id");
        query.setParameter("id", id);

        return query.executeUpdate() > 0;
    }

    @Override
    public boolean userHavePhoto(long userId, long photoId) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("from Announcement a where a.owner.id = :userId and :photoId in (select id from Photo p where p.realty.id = a.realty.id)");
        query.setParameter("userId", userId);
        query.setParameter("photoId", photoId);

        return query.list().size() > 0;
    }

    @Override
    public boolean userHavePhoto(long userId, long realtyId, long photoId) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("from Announcement a where a.owner.id = :userId and :photoId in (select id from Photo p where p.realty.id = a.realty.id and a.realty.id = :realtyId)");
        query.setParameter("userId", userId);
        query.setParameter("realtyId", realtyId);
        query.setParameter("photoId", photoId);

        return query.list().size() > 0;
    }

    @Override
    public boolean setMainPhoto(long realtyId, Long photoId) {
        Query query = sessionFactory.getCurrentSession().
                createQuery("update Realty r set r.mainPhoto.id = :photoId where r.id = :realtyId");
        query.setParameter("realtyId", realtyId);
        query.setParameter("photoId", photoId);

        return query.executeUpdate() > 0;
    }
}
